import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {UserService} from '../user.service';
import {ActivatedRoute} from '@angular/router';
import {Location} from '@angular/common';
import {Util} from '../../../public/util/util';
import {AREA_LEVEL_3_JSON} from '../../../public/util/area_level_3';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.css']
})
export class UserEditComponent implements OnInit {
  public isConfirmLoading: boolean = false;
  public code: string; //userDeposit
  public validateForm: FormGroup;//添加用户的表单
  areaCode: Array<any>;
  options = Util.transAreas(AREA_LEVEL_3_JSON);//将地区数据转成联级组件需要的格式;

  constructor(private fb: FormBuilder, private userService: UserService, private route: ActivatedRoute, public location: Location) {
    this.validateForm = this.fb.group({
      account: [null, Validators.compose([Validators.required, Validators.maxLength(32)])],
      password: [null, Validators.compose([Validators.required])],
      realName: [null, Validators.compose([Validators.required])],
      country: [null, Validators.compose([Validators.required])],
      areaCode: [null, [Validators.required]],
    });
  }

  ngOnInit() {
  }

  /**
   * 表单确认
   */
  addLeader($event) {
    $event.preventDefault();
    //1.进行脏检查，提示未填的必填字段
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.isConfirmLoading = true;
    let formData = Object.assign({},this.validateForm.value);
    formData.areaCode = formData.areaCode[2];
    //addLeader
    this.userService.addLeader(formData).then((data: any) => {
      this.isConfirmLoading = false;
      this.location.back();
    }).catch(res => this.isConfirmLoading = false)
  }

  /**
   * 响应式表单无法获取到级联选择器数据，因此使用模板式表单来获取数据，并赋值给响应式表单，以便进行脏检测
   */
  getAreas() {
    this.validateForm.controls.areaCode.patchValue(this.areaCode);
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }
}

